using Shielded.Gossip;
using System;
using System.Linq;
using System.Collections.Generic;

namespace ConsoleApp1
{
    /// <summary>
    /// 分布式一致性KV存储封装，简化一致性读写操作。
    /// </summary>
    public class DistributedStore
    {
        private readonly ConsistentGossipBackend _backend;
        public DistributedStore(ConsistentGossipBackend backend)
        {
            _backend = backend ?? throw new ArgumentNullException(nameof(backend));
        }

        /// <summary>
        /// 分布式一致性写入（同步阻塞，默认使用VecVersioned包装）
        /// </summary>
        public bool Set<T>(string key, T value, int attempts = 10)
        {
            var vec = value.Version();
            // 只关心分布式事务是否成功
            return _backend.RunConsistent(() => { _backend.SetHasVec(key, vec); }, attempts).GetAwaiter().GetResult();
        }

        /// <summary>
        /// 分布式一致性读取（同步阻塞，返回最新VecVersioned的Value）
        /// </summary>
        public bool TryGet<T>(string key, out T value, int attempts = 10)
        {
            value = default;
            var (success, multi) = _backend.RunConsistent(() => _backend.TryGetVecVersioned<T>(key), attempts).GetAwaiter().GetResult();
            if (success)
            {
                var item = multi.SingleOrDefault();
                if (typeof(T).IsValueType)
                {
                    if (!EqualityComparer<T>.Default.Equals(item.Value, default))
                    {
                        value = item.Value;
                        return true;
                    }
                }
                else
                {
                    if (item.Value != null)
                    {
                        value = item.Value;
                        return true;
                    }
                }
            }
            return false;
        }
    }
} 